<?php
namespace control;

/*
*查寝记录类
*/

class checkLiveRecordClass extends adIndexClass
{
    private const page = 'checkLiveRecord';
    private const table = 'dormitory_live';
    private const title = '查寝记录';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => '日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'dormitory' => [
                        'name'  => "宿舍号",
                        'width' => 200,
                    ],
                    'isHealth'  => [
                        'name'  => "清洁卫生",
                        'width' => 200,
                    ],
                    'isPower'         => [
                        'name'  => '大功率电器',
                        'width' => 200,
                    ],
                    'isViolation'          => [
                        'name'  => '其他违规项',
                        'width' => 300,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,
                    ],
                    'stid'          => [
                        'name'  => '查寝人',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "楼号" => repeatSelect(array('change'=>'getFloor','sqlForm'=>"dormitory where state ='启用'",'sqlField'=>'building','name'=>'building')),
                    "楼层'"     => repeatSelect(array('change'=>'getRoom','sqlForm'=>"dormitory where state ='启用' and building = ''",'sqlField'=>'floor','name'=>'floor')),
                    '宿舍号' => idSelect(array('change'=>'getPeople','sqlForm'=>"dormitory where state ='启用' and building = '' and floor = ''",'sqlField'=>'room','sqlId'=>'id','name'=>'dormitoryId')),
                ],
                [
                    '备注'   => text(array("name" => "text")),
                    "日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{id:'".self::getId()."'})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }


    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "text" => $this->post('text'),
        );
        //全等查询数组
        $equal = array(
            "dormitoryId" => $this->post('dormitoryId'),//楼号
        );
        $and = "";
        $mAnd = '';
        if (empty($this->post('dormitoryId'))){
            if ($this->post('building')){
                $mAnd.=" and building = '".$this->post('building')."'";
            }
            if ($this->post('floor')){
                $mAnd.=" and floor = '".$this->post('floor')."'";
            }
            $and.=" and dormitoryId in (select id from dormitory where 1=1 {$mAnd})";
        }
        if ($this->post('creatTime')) {
            $and .= self::timeComparison($this->post('createTime'),field: 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'".$array['id']."'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "dormitory":
                        $dormitory = query('dormitory',"id = '$array[dormitoryId]'");
                        $row[] = $dormitory['building'].'-'.$dormitory['floor'].'-'.$dormitory['room'];
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'].$this->editJs() . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $dormitory = query('dormitory',"id = '$info[dormitoryId]'");
        $dormitory['maxPeople'] = $dormitory['maxPeople']?:0;
        $livePeople = static::total(array('table'=>'dormitory_record','where'=>"dormitoryId = '".$dormitory['id']."' and state = '入住'"));
        $people = $dormitory['maxPeople']."/".$livePeople;
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate']?:$this->date]),
                ],
                [
                    must . "宿舍号：" => repeatSelect(array('title'=>'楼号','value'=>$dormitory['building'],'change'=>'getFloor','sqlForm'=>"dormitory where state ='启用'",'sqlField'=>'building','name'=>'building')).
                        repeatSelect(array('title'=>'楼层','value'=>$dormitory['floor'],'change'=>'getRoom','sqlForm'=>"dormitory where state ='启用' and building = '$dormitory[building]'",'sqlField'=>'floor','name'=>'floor')).
                        idSelect(array('title'=>'宿舍号','change'=>'getPeople','value'=>$dormitory['id'],'sqlForm'=>"dormitory where state ='启用' and building = '$dormitory[building]' and floor = '$dormitory[floor]'",'sqlField'=>'room','sqlId'=>'id','name'=>'dormitoryId')),
                ],
                [
                    "可住/已住"=>"<span id='livePeople'>{$people}</span>"
                ],
                [
                    "清洁卫生：" => radio(array('name'=>'isHealth','value'=>['合格','不合格'],'checked'=>$info['isHealth']?:'合格')),
                ],
                [
                    "大功率电器：" => radio(array('name'=>'isPower','value'=>['合格','不合格'],'checked'=>$info['isPower']?:'合格')),
                ],
                [
                    "其他违规项：" => radio(array('name'=>'isViolation','value'=>['合格','不合格'],'checked'=>$info['isViolation']?:'合格')),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                ],
            ],
        ]);

        //返回
        return $this->layer(array("title" => "编辑", "height" => 450, "width" => 800, "html" => $html));
    }

    /**
     *
     * @return string
     */
    public function editJs(): string
    {
        return <<<eof
<script>
function getFloor(e){
    $.post(root+'control/adIndex.html?cla=dormitoryRecord&fun=getFloor',{building:e.value},function(res) {
           $(e).parent().find("[name='floor']").empty().append(res.floorHtml);
         $(e).parent().find("[name='dormitoryId']").empty().append(res.roomHtml);
         $("#livePeople").html('-/-');
    },'json')
}
function getRoom(e){
     let building= $(e).parent().find("[name='building']").val();
     $.post(root+'control/adIndex.html?cla=dormitoryRecord&fun=getRoom',{floor:e.value,building:building},function(res) {
       $(e).parent().find("[name='dormitoryId']").empty().append(res.roomHtml);
    },'json')
}
function getPeople(e){
     $.post(root+'control/adIndex.html?cla=dormitoryRecord&fun=getPeople',{dormitoryId:e.value},function(res) {
        $("#livePeople").html(res.html);
    },'json')
}
</script>
eof;

    }
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'recordDate' => $this->post('recordDate'),
            'dormitoryId' => $this->post('dormitoryId'),
            'isHealth' => $this->post('isHealth'),
            'isPower' => $this->post('isPower'),
            'isViolation' => $this->post('isViolation'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'recordDate' => '日期',
            'dormitoryId' => '宿舍号',
        ];
        $rules = [
            'recordDate' => 'required',
            'dormitoryId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(static::total(array('table'=>self::table,'where'=>"dormitoryId = '$field[dormitoryId]' and recordDate = '$field[recordDate]' and id !='$id'")) >0){
            $json['warn'] = '此宿舍已已有查寝记录';
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power =$word= '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word'=>$word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

